package com.imot.scheduler;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.imot.pojo.entity.SoftwareUsage;
import com.imot.service.ISoftwareUsageService;
import lombok.RequiredArgsConstructor;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;

/**
 * ClassName: SoftUsageTask
 * Description:
 * date: 2023/11/9 17:40
 *
 * @author imot-jiah.wang
 */
@Component
@RequiredArgsConstructor
public class SoftUsageTask {
    private final ISoftwareUsageService softwareUsageService;

    @Scheduled(fixedRate = 5000)
    private void updateUsageTask(){
        LocalDate date = LocalDate.now();
        LocalDateTime dateTime = LocalDateTime.now();
        LocalDateTime start = LocalDateTime.of(date, LocalTime.MIN);
        LocalDateTime end = LocalDateTime.of(date, LocalTime.MAX);

        LambdaQueryWrapper<SoftwareUsage> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.ge(SoftwareUsage::getStartTime,start);
        queryWrapper.le(SoftwareUsage::getStartTime,end);
        queryWrapper.orderByDesc(SoftwareUsage::getId);
        queryWrapper.last("limit 1");

        SoftwareUsage usage = softwareUsageService.getOne(queryWrapper);
        if (usage==null){
            SoftwareUsage softwareUsage = new SoftwareUsage();
            softwareUsage.setStartTime(dateTime);
            softwareUsage.setEndTime(dateTime);
            softwareUsageService.save(softwareUsage);
        }else {
            Duration duration = Duration.between(usage.getEndTime(), dateTime);
            long minutes = duration.toMinutes();
            if (minutes>15){
                SoftwareUsage softwareUsage = new SoftwareUsage();
                softwareUsage.setStartTime(start);
                softwareUsage.setEndTime(end);
                softwareUsageService.save(softwareUsage);
            }else {
                usage.setEndTime(dateTime);
                softwareUsageService.updateById(usage);
            }
        }
        SoftwareUsage usage2 = softwareUsageService.getOne(queryWrapper);
        LocalDateTime startTime = usage2.getStartTime();
        LocalDateTime endTime = usage2.getEndTime();
        Duration duration = Duration.between(startTime, endTime);
        long minutes = duration.toMinutes();
        usage2.setDuration((int)minutes);
        softwareUsageService.updateById(usage2);
    }
}

